<template>
  <div class="view">
    <span class="view-title">申请单列表</span>
    <!--没有上级的用户不需要申请用车,所以申请用车按钮是灰色 :disabled="user.parentId==null"-->
    <el-button class="title-right-button" @click="handleCreate" :disabled="user.parentId==null" type="primary">申请用车</el-button>
  </div>
  <!-- 申请用车弹窗 -->
  <el-dialog class="dialog" title="创建申请单" :before-close="handleClose" v-model="addApplicationDialogVisible">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="用车人">
            <el-input readonly :value="user.username"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用时间">
            <el-date-picker
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="times"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="车辆出发地">
            <el-input placeholder="请输入" v-model="addForm.departureAddr"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车辆目的地">
            <el-input placeholder="请输入" v-model="addForm.destinationAddr"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="用车事由">
            <el-input placeholder="请输入" v-model="addForm.reason" type="textarea" resize="none" :rows="3"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input placeholder="请输入" v-model="addForm.remark" type="textarea" resize="none" :rows="3"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="驾照">
            <el-upload
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl"/>
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审批人">
            <el-row :gutter="10">
              <el-col :span="12" v-if="auditUserOptions.length>0">
                <el-tag type="primary">
                  <el-icon style="margin-right:5px;position:relative;top:2px;">
                    <User/>
                  </el-icon>
                  <span>{{ auditUserOptions[0].username }}</span>
                </el-tag>
              </el-col>
              <el-col :span="12" v-if="auditUserOptions.length>1">
                <el-tag type="primary">
                  <el-icon style="margin-right:5px;position:relative;top:2px;">
                    <User/>
                  </el-icon>
                  <span>{{ auditUserOptions[1].username }}</span>
                </el-tag>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button @click="addApplication" type="primary">确定</el-button>
    </template>
  </el-dialog>

  <!-- 用车申请列表 搜索卡片 -->
  <el-card class="table-card">
    <el-form style="padding-top:10px;">
      <el-row :gutter="30">
        <el-col :span="5">
          <el-form-item label="出发地">
            <el-input placeholder="请输入出发地"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="目的地">
            <el-input placeholder="请输入目的地"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="申请单状态">
            <el-select placeholder="请选择">
              <el-option label="已发起" value="10"></el-option>
              <el-option label="撤销" value="20"></el-option>
              <el-option label="审核中" value="30"></el-option>
              <el-option label="驳回" value="40"></el-option>
              <el-option label="已通过" value="50"></el-option>
              <el-option label="分配用车" value="60"></el-option>
              <el-option label="工单结束" value="70"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <el-button @click="resetSearch">重置</el-button>
            <el-button @click="loadApplication" type="primary">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <!-- 用车申请表格 -->
  <el-card class="table-card">
    <el-table>
      <el-table-column type="index" width="80" align="center" prop="id" label="编号"></el-table-column>
      <el-table-column align="center" prop="username" label="申请人"></el-table-column>
      <el-table-column align="center" prop="departureAddr" label="出发地"></el-table-column>
      <el-table-column align="center" prop="destinationAddr" label="目的地"></el-table-column>
      <el-table-column align="center" prop="reason" label="用车原因"></el-table-column>
      <el-table-column align="center" prop="auditUsernameList" label="审批人"></el-table-column>
      <el-table-column align="center" prop="startTime" label="使用开始时间"></el-table-column>
      <el-table-column align="center" prop="endTime" label="使用结束时间"></el-table-column>
      <el-table-column align="center" prop="status" label="申请单状态"></el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" link>撤销</el-button>
        </template>
      </el-table-column>
    </el-table>

  </el-card>
  <!--  <el-upload-->
  <!--      v-model:file-list="fileList"-->
  <!--      v-model:action="actionUrl"-->
  <!--      name="file"-->
  <!--      limit="1"-->
  <!--      list-type="picture-card"-->
  <!--      :on-preview="handlePictureCardPreview"-->
  <!--      :on-remove="handleRemove"-->
  <!--  >-->
  <!--    <el-icon>-->
  <!--      <Plus/>-->
  <!--    </el-icon>-->
  <!--  </el-upload>-->

  <!--  <el-dialog v-model="dialogVisible">-->
  <!--    <img w-full :src="dialogImageUrl"/>-->
  <!--  </el-dialog>-->
  <!--  <hr>-->
  <!--  <h4>显示后端返回的图片路径: <span>{{tempImgUrl}}</span></h4>-->
  <!--  <img :src="BASE_URL+tempImgUrl" alt="">-->
</template>

<script setup>
import {onMounted, ref} from 'vue'
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";

//定义数组用来保存上传的图片对象
const fileList = ref([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

//定义变量用来保存图片提交的后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//处理图片的删除功能:点击图片上的"垃圾桶"图标时触发
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除图片的路径,这个路径就是后端上传Controller返回的 日期路径+文件名
  let imgUrl = uploadFile.response.data;
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('删除成功');
        } else {
          ElMessage.error(response.data.msg);
        }
      });
}
//定义一个变量用来保存上传的图片路径
const tempImgUrl = ref('');
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
  //打印上传的图片对象
  console.log(fileList.value);
  console.log(fileList.value[0]);
  //获取上传的图片路径
  tempImgUrl.value = fileList.value[0].response.data;
}
const user = ref(getCurrentUser());
const addApplicationDialogVisible = ref(false);
const handleCreate = () => {
  addApplicationDialogVisible.value = true;
}
onMounted(() => {
  loadAuditUser();
  loadApplication();
  // console.log(user.value);
});
//定义数组用来保存新增申请单时显示的审批人(含姓名)
const auditUserOptions = ref([]);
//定义数组用来保存新增申请单时,对应申请人的id,入库使用
const auditUserIdList = ref([]);
const loadAuditUser = () => {
  let parentId = user.value.parentId;
  // console.log(user.value);
  axios.get(BASE_URL + '/v1/user/select/audit/' + parentId)
      .then((response) => {
        if (response.data.code == 2000) {
          //将后端返回的数组赋值给auditUserOptions
          auditUserOptions.value = response.data.data;
          for (let i = 0; i < auditUserOptions.value.length; i++) {
            auditUserIdList.value[i] = auditUserOptions.value[i].id;
          }
        } else {
          ElMessage.error(response.data.msg);
        }
      });
}
const handleClose = () => {
  // ElMessageBox.confirm(
  //     '数据将不会保存,确认离开吗?',
  //     '警告',
  //     {
  //       confirmButtonText: '确认',
  //       cancelButtonText: '取消',
  //       type: 'warning',
  //     }
  // )
  //     .then(() => {
        addApplicationDialogVisible.value = false;
      //   fileList.value = [];
      //   times.value = [];
      //   addForm.value = {};
      // })
      // .catch(() => {
      //   ElMessage({
      //     type: 'info',
      //     message: '操作取消',
      //   })
      // });
}
//定义数组用来保存申请单的起止时间
const times = ref([]);
//定义对象用来保存申请单的表单数据
const addForm = ref({
  departureAddr: '',
  destinationAddr: '',
  reason: '',
  remark: ''
});
//定义方法发送新增申请单的请求
const addApplication = () => {
  if (fileList.value.length == 0) {
    ElMessage.warning('请上传图片');
    return;
  }
  addForm.value.startTime = times.value[0];
  addForm.value.endTime = times.value[1];
  addForm.value.username = user.value.username;
  addForm.value.id = user.value.id;
  addForm.value.imgUrl = fileList.value[0].response.data;
  addForm.value.auditUserIdList = auditUserIdList.value;
  console.log(addForm.value);

  let data = qs.stringify(addForm.value);
  axios.post(BASE_URL + '/v1/application/save', data)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('新增成功');
          addApplicationDialogVisible.value = false;
          fileList.value = [];
          times.value = [];
          addForm.value = {};
        } else {
          ElMessage.error(response.data.msg);
        }
      });
}


//准备数组用来保存查出来的申请单表格数据
const tableData = ref([]);
//准备对象用来保存搜索条件
const searchApplication = ref({
  departureAddr: '',//出发地
  destinationAddr: '',//目的地
  status:''//申请单状态
});
//定义加载申请单的方法
const loadApplication = ()=>{
  let data = qs.stringify(searchApplication.value);
  axios.get(BASE_URL+'/v1/application/select?'+data).then((response)=>{
    if (response.data.code==2000){
      tableData.value = response.data.data;
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}
//定义重置搜索条件的方法
const resetSearch = ()=>{
  searchApplication.value = {};
  loadApplication();
}
</script>

<style scoped>
.view {
  height: 4vh;
  padding: 5px 20px;
  background-color: #fff;
}

.view-title {
  line-height: 40px;
  font-size: 20px;
  font-weight: bold;
}

.title-right-button {
  float: right;
  margin-top: 3px;
}

.dialog {
  width: 1000px;
  padding: 40px;
}

.search-card {
  margin: 20px;
  height: 70px;
}

.table-card {
  margin: 20px;
}
</style>